package com.dom;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.print.Doc;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;

public class DomReader {
    //循环得到收藏信息.xml里的所有节点内容
    @Test
    public void testDomShow() throws Exception {
        //得到Dom解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析xml文档，得到一个Document对象，即DOM树
        Document doc = db.parse("src/main/resources/收藏信息.xml");
        //得到所有Brand节点列表信息
        NodeList brandList = doc.getElementsByTagName("Brand");
        //循环Brand信息
        for (int i = 0; i < brandList.getLength(); i++) {
            //获取第一个Brand元素
            Node brand = brandList.item(i);
                //获取第一个i的Brand元素的name属性值
                Element element = (Element) brand;
                String attrValue = element.getAttribute("name");
                //获取第i个Brand元素的所有子元素的name属性
                NodeList types = element.getChildNodes();
                for (int j = 0; j < types.getLength(); j++) {
                    //判断是否是元素节点，，如果为true，则表示是想要的元素
                    if (types.item(j).getNodeType() == Node.ELEMENT_NODE) {
                        //type节点
                        Element typeElement = ((Element) types.item(j));
                        //获得手机型号
                        String type = typeElement.getAttribute("name");
                        System.out.println("手机：" + attrValue+"，类型："+type);
                    }
                }
        }
    }

    //读取文本节点
    @Test
    public void testTestNode()throws Exception{
       //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //解析xml文档，得到一个Document对象，即DOM树
        Document doc=db.parse("src/main/resources/PhoneInfo2.xml");
        //读取pubDa
        NodeList list=doc.getElementsByTagName("pubDate");
        //pubDate元素节点
        Element pubDateElement=(Element) list.item(0);
        //读取文本节点
        String pubDate=pubDateElement.getFirstChild().getNodeValue();
        System.out.println(pubDate);
    }

    /**
     *循环得到收藏信息.xml里的所有节点内容
     */
    @Test
    public void testAddDom()throws Exception{
      //工厂
        DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
        //DOM构建器
        DocumentBuilder builder=factory.newDocumentBuilder();
        //解析xml生成dom树
        Document doc=builder.parse("src/main/resources/收藏信息.xml");
        //获取根节点
        Element phoneInfoEl=doc.getDocumentElement();
        //用标签名获取节点列表
        NodeList brandList=phoneInfoEl.getElementsByTagName("Brand");
        //System.out.println(brandList.getLength());
        for(int i=0;i<brandList.getLength();i++){
        //Brand元素
            Element brandEl=(Element) brandList.item(i);
            //name属性
            String nameAttr=brandEl.getAttribute("name");
            //Type类型集合
            NodeList typeList=brandEl.getElementsByTagName("Type");
            for (int j = 0; j <typeList.getLength() ; j++) {
                Element typeEl=(Element) typeList.item(j);
                String typeName=typeEl.getAttribute("name");
                System.out.println("手机品牌："+nameAttr+"，型号："+typeName);
            }
        }
    }


    /**
     * 添加节点2
     */
    @Test
    public void testAddNode()throws Exception{
        //工厂
        DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
        //DOM构建器
        DocumentBuilder builder=factory.newDocumentBuilder();
        //解析xml生成dom树
        Document doc=builder.parse("src/main/resources/收藏信息.xml");
        //获取根节点
        Element phoneInfoEl=doc.getDocumentElement();

        Element brandEl=doc.createElement("Brand"); //创建父节点
        brandEl.setAttribute("name","三星"); //在父节点里创建值
        Element typeEl=doc.createElement("Type");
        typeEl.setAttribute("name","NodeX");

        //建立Brand和Type关系，让Type成为Brand的子节点，加入进来
        brandEl.appendChild(typeEl);
        //建立PhoneInfo和Brand关系，让Brand成为PhoneInfo
        phoneInfoEl.appendChild(brandEl);

        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        //转换器
        Transformer transformer=transformerFactory.newTransformer();
        //设置输出属性
        transformer.setOutputProperty("encoding","UTF-8");
        //把DOM转成DomSource
        DOMSource dos=new DOMSource(doc);
        StreamResult sr=new StreamResult(new FileOutputStream("D:/新收藏信息.xml"));
        //把DOM树转为xml文件
        transformer.transform(dos,sr);
    }


    /**
     * 删除
     */
    public void testDelete()throws Exception{
        //工厂
        DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
        //DOM构建器
        DocumentBuilder builder=factory.newDocumentBuilder();
        //解析xml生成dom树
        Document doc=builder.parse("src/main/resources/收藏信息.xml");
        //获取根节点
        Element phoneInfoEl=doc.getDocumentElement();
        phoneInfoEl.removeChild(phoneInfoEl.getElementsByTagName("Brand").item(1)); //删除第一个Brand后面的所有节点

        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        //转换器
        Transformer transformer=transformerFactory.newTransformer();
        //设置输出属性
        transformer.setOutputProperty("encoding","UTF-8");
        //把DOM转成DomSource
        DOMSource dos=new DOMSource(doc);
        StreamResult sr=new StreamResult(new FileOutputStream("D:/新收藏信息.xml"));
        //把DOM树转为xml文件
        transformer.transform(dos,sr);
    }


    //修改
    @Test
    public void testUpdate()throws Exception{
        //工厂
        DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
        //DOM构建器
        DocumentBuilder builder=factory.newDocumentBuilder();
        //解析xml生成dom树
        Document doc=builder.parse("src/main/resources/收藏信息.xml");
      //找到修改的节点
        NodeList list=doc.getElementsByTagName("Brand");
        for(int i=0;i< list.getLength();i++){
            Element brandElement=(Element) list.item(i);
            String brandName=brandElement.getAttribute("name");
            if(brandName.equals("三星")){
                //修改属性，？？？为什么添加字母，或者中文，就会乱码，就会除了本字段，其他字段全改了
                brandElement.setAttribute("name","111");
            }
        }
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        //转换器
        Transformer transformer=transformerFactory.newTransformer();
        //设置输出属性
        transformer.setOutputProperty("encoding","UTF-8");
        //把DOM转成DomSource
        DOMSource dos=new DOMSource(doc);
        StreamResult sr=new StreamResult(new FileOutputStream("src/main/resources/收藏信息.xml"));
        //把DOM树转为xml文件
        transformer.transform(dos,sr);
    }


    //删除？？？有bug，删完之后就会乱码
    @Test
    public void testDelete2()throws Exception{
        //工厂
        DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
        //DOM构建器
        DocumentBuilder builder=factory.newDocumentBuilder();
        //解析xml生成dom树
        Document doc=builder.parse("src/main/resources/收藏信息.xml");
        //找到要删除的节点
        NodeList list=doc.getElementsByTagName("Brand");
        for(int i=0;i<list.getLength();i++){
            Element brandElement=(Element) list.item(i);
            String brandName=brandElement.getAttribute("name");
            if(brandName.equals("111")){
              brandElement.getParentNode().removeChild(brandElement);
            }
        }
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        //转换器
        Transformer transformer=transformerFactory.newTransformer();
        //设置输出属性
        transformer.setOutputProperty("encoding","UTF-8");
        //把DOM转成DomSource
        DOMSource dos=new DOMSource(doc);
        StreamResult sr=new StreamResult(new FileOutputStream("src/main/resources/收藏信息.xml"));
        //把DOM树转为xml文件
        transformer.transform(dos,sr);
    }


}
